import { InputItem as AntInput } from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import ContractSelectModal from '@/components/ContractSelectModal';
import { IOrgTreeCheckedItem } from '../../contract-select/interface';
import { connect } from 'react-redux';
import { ConnectState, ConnectProps } from 'typings/connect';
import './index.less';

export class DeptSelect extends React.Component<Props & ConnectProps, State> {
  public static defaultProps = new Props();
  public state = new State();

  constructor(props: Props) {
    super(props);

    this.state = {
      modalStatus: false,
      showDeptText: '',
      receiveData: []
    };
  }

  UNSAFE_componentWillMount() {
    this.setReceiveData();
  }

  componentDidUpdate() {
    this.setReceiveData();
  }

  componentDidMount() {
    this.props.getOrgTree();
  }

  setReceiveData = () => {
    if (this.state.receiveData.length) return;
    const { props: { form, code } } = this;
    let value = form?.getFieldValue(code);
    if (value && !Array.isArray(value)) value = [value];
    if (!value) return;
    this.setState({
      receiveData: value
    });
  }

  onInit = (checkedItems: IOrgTreeCheckedItem[]) => {
    const texts = checkedItems ? checkedItems.map((el) => el.title) : [];
    const showDeptText = texts.join(';') || '';
    this.setState({
      showDeptText
    });
  };

  dealDeptshowDeptText(data: { map: (arg0: (item: any) => any) => any[]; text: any }) {
    if (Array.isArray(data)) {
      return data?.map((item) => item.text).join(';');
    } else {
      return data?.text;
    }
  }

  handleKeyPress = () => {
    this.setState({ modalStatus: true });
    document.documentElement.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
  };

  closeModal() {
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
    this.setState({ modalStatus: false });
  }

  onSubmit = (isHandle: boolean, values: IOrgTreeCheckedItem[], fieldProps: any) => {
    const result = values?.map((el) => {
      return {
        value: el.key,
        text: el.title,
        type: el.type
      };
    });
    this.setState({
      modalStatus: false
    });
    const { props: { form, code } } = this;
    document.documentElement.style.overflow = '';
    document.body.style.overflow = '';
    const formatResult = this.props.multiple ? result : result[0]; // 单选值为部门，多选值为数组
    //先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
    if (isHandle) fieldProps?.onChange(result);
    this.props.onChange && this.props.onChange(formatResult);
    form && form.setFieldsValue({ [code]: formatResult });
  };

  getCheckedValue = () => {
    const { props: { form, code } } = this;
    const value = form?.getFieldValue(code);
    if (!value) {
      return '';
    }
    if (!Array.isArray(value)) return value.text;
    const texts = value?.map(({ text }) => text);
    return texts.join(';');
  };

  onClear = () => {
    this.props.onChange && this.props.onChange(undefined);
  };

  public render() {
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    const { getFieldProps } = this.props.form || {};
    const {
      form,
      name,
      orgTree,
      ...otherProps
    } = this.props;

    let fieldProps: any = {};

    if (getFieldProps) {
      fieldProps = {
        ...getFieldProps(this.props.code, {
          rules: [
            { required: this.props.required, message: `请选择${name}` }
          ]
        })
      };
    }

    return (
      <>
        <div className="deptWrap" onClick={this.handleKeyPress}>
          <AntInput
            title={form ? form.getFieldValue(this.props.code) : ''}
            {...otherProps}
            {...fieldProps}
            disabled
            // showClear={isContent}
            value={this.getCheckedValue()}
            extra={<i className="icon iconfont" style={{ fontSize: '16px', color: '#d1d1d1', position: 'relative', right: '-0.6vw' }}>&#xe6ed;</i>}
            style={{ color: '#222222' }}
          >
            {name}
          </AntInput>

        </div>
        <ContractSelectModal
          modalStatus={this.state.modalStatus}
          closeModal={this.closeModal.bind(this)}
          submit={(isHandle: boolean, value: any[]) => { this.onSubmit(isHandle, value, fieldProps); }}
          type={'dept'}
          receiveData={this.state.receiveData}
          mode={this.props.multiple ? 'multiple' : 'single'}
          orgData={orgTree}
        />
      </>
    );
  }
}

const mapStateToProps = (state: ConnectState) => ({
  orgTree: state.common.orgTree
});

const mapDispatchToProps = (dispatch) => ({
  getOrgTree: () => dispatch({ type: 'common/getOrgTreeDataSaga' })
});

export const DeptSelectWithConnect = connect(mapStateToProps, mapDispatchToProps)(DeptSelect);
